#!/bin/bash

# 设置日志文件路径
LOG_FILE="/var/log/mysql_install.log"
TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")

# 创建日志文件并设置权限
touch "$LOG_FILE"
chmod 644 "$LOG_FILE"

# 函数：记录日志并输出到终端
log() {
    echo -e "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# 函数：执行命令并记录输出
run_cmd() {
    log "执行命令: $1"
    eval "$1" >> "$LOG_FILE" 2>&1
    local status=$?
    if [ $status -ne 0 ]; then
        log "命令执行失败 (状态码 $status): $1"
        return $status
    fi
    return 0
}

# 检查是否以root用户运行
if [ "$(id -u)" -ne 0 ]; then
    log "请使用root用户运行此脚本！"
    exit 1
fi

log "===== MySQL 安装开始 ====="

# 检查MySQL安装包是否存在
MYSQL_TAR=$(ls mysql-*.tar.* 2>/dev/null | head -n1)
if [ -z "$MYSQL_TAR" ]; then
    log "未找到MySQL安装包！请将mysql.tar.gz文件放在当前目录。"
    exit 1
fi
log "找到安装包: $MYSQL_TAR"

# 安装必要依赖
log "安装必要依赖..."
run_cmd "yum install -y libaio numactl ncurses-compat-libs"

# 清理旧安装
log "清理旧安装..."
run_cmd "systemctl stop mysql 2>/dev/null"
run_cmd "systemctl disable mysql 2>/dev/null"
run_cmd "rm -rf /usr/local/mysql*"
run_cmd "rm -f /etc/systemd/system/mysql.service"
run_cmd "rm -f /etc/my.cnf"
run_cmd "rm -f /etc/profile.d/mysql.sh"
run_cmd "rm -f /var/run/mysqld/mysqld.pid"
run_cmd "pkill -9 mysqld"

# 解压安装包
log "解压安装包: $MYSQL_TAR"
MYSQL_DIR=""

if [[ "$MYSQL_TAR" == *.tar.xz ]]; then
    run_cmd "tar xJf \"$MYSQL_TAR\" -C /usr/local"
    MYSQL_DIR=$(tar tJf "$MYSQL_TAR" | head -1 | cut -f1 -d"/")
elif [[ "$MYSQL_TAR" == *.tar.gz ]]; then
    run_cmd "tar xzf \"$MYSQL_TAR\" -C /usr/local"
    MYSQL_DIR=$(tar tzf "$MYSQL_TAR" | head -1 | cut -f1 -d"/")
else
    log "不支持的压缩格式: $MYSQL_TAR"
    exit 1
fi

# 验证解压目录
if [ -z "$MYSQL_DIR" ] || [ ! -d "/usr/local/$MYSQL_DIR" ]; then
    log "解压目录验证失败！"
    exit 1
fi
log "解压到目录: /usr/local/$MYSQL_DIR"

# 创建MySQL目录和用户
log "创建MySQL用户和目录..."
run_cmd "ln -sf \"/usr/local/$MYSQL_DIR\" /usr/local/mysql"
if ! id -u mysql >/dev/null 2>&1; then
    run_cmd "groupadd mysql"
    run_cmd "useradd -r -g mysql -s /bin/false mysql"
fi

# 创建数据目录和sock目录
log "创建数据目录并设置权限..."
run_cmd "mkdir -p /data/mysql"
run_cmd "mkdir -p /var/lib/mysql"
run_cmd "mkdir -p /var/run/mysqld"

# 关键权限修复：创建并设置错误日志文件权限
log "设置错误日志文件权限..."
run_cmd "touch /var/log/mysqld.log"
run_cmd "chown mysql:mysql /var/log/mysqld.log"
run_cmd "chmod 640 /var/log/mysqld.log"

# 设置目录所有权
run_cmd "chown -R mysql:mysql /data/mysql"
run_cmd "chown -R mysql:mysql /var/lib/mysql"
run_cmd "chown -R mysql:mysql /var/run/mysqld"

# SELinux 配置（如果启用）
if [ -x "/usr/sbin/sestatus" ] && /usr/sbin/sestatus | grep -q "enabled"; then
    log "配置SELinux策略..."
    run_cmd "yum install -y policycoreutils-python"
    run_cmd "semanage fcontext -a -t mysqld_log_t '/var/log/mysqld.log'"
    run_cmd "semanage fcontext -a -t mysqld_db_t '/data/mysql(/.*)?'"
    run_cmd "semanage fcontext -a -t mysqld_var_run_t '/var/run/mysqld(/.*)?'"
    run_cmd "restorecon -Rv /var/log/mysqld.log"
    run_cmd "restorecon -Rv /data/mysql"
    run_cmd "restorecon -Rv /var/run/mysqld"
fi

# 初始化数据库
log "初始化MySQL数据库..."
run_cmd "/usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --basedir=/usr/local/mysql --datadir=/data/mysql"

# 创建配置文件
log "创建配置文件..."
cat > /etc/my.cnf << EOF
[mysqld]
basedir=/usr/local/mysql
datadir=/data/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

# 性能优化
innodb_buffer_pool_size=128M
innodb_log_file_size=48M
max_connections=100

[mysql]
socket=/var/lib/mysql/mysql.sock

[client]
socket=/var/lib/mysql/mysql.sock
EOF
log "配置文件 /etc/my.cnf 已创建"

# 创建systemd服务文件
log "创建systemd服务..."
cat > /etc/systemd/system/mysql.service << EOF
[Unit]
Description=MySQL Server
After=network.target

[Service]
User=mysql
Group=mysql
Type=forking

# PID文件处理
PIDFile=/var/run/mysqld/mysqld.pid

# 权限修复
PermissionsStartOnly=true
ExecStartPre=/bin/mkdir -p /var/run/mysqld
ExecStartPre=/bin/chown -R mysql:mysql /var/run/mysqld
ExecStartPre=/bin/chmod 0755 /var/run/mysqld
ExecStartPre=/bin/touch /var/log/mysqld.log
ExecStartPre=/bin/chown mysql:mysql /var/log/mysqld.log
ExecStartPre=/bin/chmod 640 /var/log/mysqld.log

# 启动命令
ExecStart=/usr/local/mysql/bin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid

Restart=on-failure
RestartSec=5
TimeoutSec=300

[Install]
WantedBy=multi-user.target
EOF
log "systemd服务文件 /etc/systemd/system/mysql.service 已创建"

# 配置环境变量 - 关键修复：确保mysql客户端在PATH中
log "配置环境变量..."
echo 'export PATH=$PATH:/usr/local/mysql/bin' > /etc/profile.d/mysql.sh
# 立即生效当前环境
export PATH=$PATH:/usr/local/mysql/bin
source /etc/profile
# 验证mysql命令是否可用
if ! command -v mysql &> /dev/null; then
    log "警告：mysql命令仍不可用，尝试修复PATH..."
    run_cmd "source /etc/profile"
    if ! command -v mysql &> /dev/null; then
        log "错误：无法找到mysql命令，请手动检查"
    else
        log "mysql命令修复成功"
    fi
else
    log "mysql命令可用"
fi

# 启动MySQL服务前确保权限
log "启动前权限检查..."
run_cmd "chown -R mysql:mysql /var/run/mysqld"
run_cmd "chown mysql:mysql /var/log/mysqld.log"
run_cmd "chmod 750 /var/run/mysqld"
run_cmd "chmod 640 /var/log/mysqld.log"
run_cmd "rm -f /var/run/mysqld/mysqld.pid"  # 确保没有旧的PID文件

# 启动MySQL服务
log "启动MySQL服务..."
run_cmd "systemctl daemon-reload"
run_cmd "systemctl enable mysql"
run_cmd "systemctl start mysql"

# 等待MySQL启动
log "等待MySQL启动..."
sleep 5

# 检查服务状态
if systemctl is-active --quiet mysql; then
    log "MySQL服务已成功启动"
else
    log "MySQL启动失败，尝试获取状态..."
    run_cmd "systemctl status mysql"

    log "检查错误日志..."
    [ -f "/var/log/mysqld.log" ] && tail -n 50 "/var/log/mysqld.log" | tee -a "$LOG_FILE"

    log "尝试手动启动MySQL进行诊断..."
    /usr/local/mysql/bin/mysqld --user=mysql --console 2>&1 | tee -a "$LOG_FILE"

    exit 1
fi

# 生成随机密码
RANDOM_PASS=$(openssl rand -base64 12 | tr -dc 'a-zA-Z0-9!@#$%^&*()_+' | head -c 16)
log "生成随机root密码: $RANDOM_PASS"

# 安全设置 - 使用绝对路径确保mysql命令可用
log "进行安全设置..."
/usr/local/mysql/bin/mysql -u root << EOF 2>> "$LOG_FILE"
ALTER USER 'root'@'localhost' IDENTIFIED BY '$RANDOM_PASS';
DELETE FROM mysql.user WHERE User='';
FLUSH PRIVILEGES;
EOF

# 验证安全设置
log "验证root用户设置..."
/usr/local/mysql/bin/mysql -u root -p"$RANDOM_PASS" -e "SELECT version();" 2>> "$LOG_FILE"
if [ $? -ne 0 ]; then
    log "警告：root密码设置可能失败"
    log "尝试使用空密码登录..."
    /usr/local/mysql/bin/mysql -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$RANDOM_PASS';" 2>> "$LOG_FILE"
    if [ $? -eq 0 ]; then
        log "密码修复成功"
    else
        log "密码设置失败，请手动修复"
    fi
else
    log "root密码验证成功"
fi

# 输出安装信息
log "===== MySQL 安装完成 ====="
log "安装摘要:"
log "  数据目录: /data/mysql"
log "  配置文件: /etc/my.cnf"
log "  错误日志: /var/log/mysqld.log"
log "  PID文件: /var/run/mysqld/mysqld.pid"
log "  安装日志: $LOG_FILE"
log "  root密码: $RANDOM_PASS"
log "  服务管理: systemctl [start|stop|status] mysql"
log "  MySQL客户端: /usr/local/mysql/bin/mysql -u root -p"
log "================================================"
log "请立即记录root密码并妥善保存！"
log "================================================"

echo -e "\n===== 安装完成 ====="
echo "安装日志已保存至: $LOG_FILE"
echo "root密码: $RANDOM_PASS"
echo "MySQL客户端路径: /usr/local/mysql/bin/mysql"
echo "使用命令登录: /usr/local/mysql/bin/mysql -u root -p"
echo "或执行: source /etc/profile 后使用 mysql -u root -p"
